<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad">

      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   @click="handleDelete">删 除
        </el-button>
      </template>
      <template slot="menuLeft">
        <el-button type="warning" icon="el-icon-back" size="small" @click.stop="goBack()">返回列表</el-button>
      </template>
    </avue-crud>
    <div class="custom-text" style="z-index: 999;font-size: 15px;color: #606266">{{ historyDataNum }}</div>
  </basic-container>
</template>

<script>
import {
  getList,
  add,
  update,
  remove,
  getSchoolUserSelect
} from "@/api/forum/userGroupList";
import {mapGetters} from "vuex";
import {contrastTime} from "@/util/validate";

export default {
  props: {
    csId: {
      type: String,
      default: '0'
    }, showMainView: {
      type: Function,
      default: null
    }
  },
  data() {
    return {
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'auto',
        calcHeight: 260,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        viewBtn: true,
        selection: true,
        // menu: false,
        column: [
          {
            label: "主键",
            prop: "id",
            rules: [{
              required: true,
              message: "请输入主键",
              trigger: "blur"
            }],
            hide: true,
            display: false
          },
          {
            label: "学校名称",
            prop: "schoolId",
            search: true,
            cascader: ['userId'],
            span: 24,
            rules: [{
              required: true,
              message: "请选择学校",
              trigger: "blur"
            }],
            type: "tree",
            dicUrl: "/api/PcPublicService/GetSchoolTreeSelect",
            props: {
              label: "xxName",
              value: "id"
            },
            change: ({value}) => {
              this.form.schoolId = value
              this.getSchoolUserSelect(value);
            }
          },
          {
            label: "用户类型",
            prop: "userType",
            type: "select",
            search: true,
            span: 24,
            cascader: ['userId'],
            rules: [{
              required: true,
              message: "请选择用户类型",
              trigger: "click"
            }],
            dicData: [
              {
                label: "教师（校长）",
                value: 2
              },
              {
                label: "家长",
                value: 3
              },
            ],
            value: 2,
            hide: false,
            change: ({value}) => {
              this.form.userType = value
              this.getSchoolUserSelect(value);
            }
          },
          {
            label: "用户名称",
            prop: "userId",
            span: 24,
            hide:true,
            editDisplay: true,
            viewDisplay: true,
            addDisplay: true,
            rules: [{
              required: true,
              message: "请选择用户",
              trigger: "blur"
            }],
            multiple: true,
            type: "select",
            dicData: [],
            props: {
              label: "title",
              value: "id"
            },
          },
          {
            label: "用户名称",
            prop: "userName",
            // search: true,
            editDisplay: false,
            viewDisplay: false,
            addDisplay: false,
            span: 24,
            rules: [{
              required: true,
              message: "请选择用户",
              trigger: "blur"
            }]
          },


        ],
      },
      historyDataNum: '',
      data: []
    };
  },
  computed: {
    ...mapGetters(["permission", "JSuserInfo"]),
    permissionList() {
      return {
        addBtn: true,//this.vaildData(this.permission.jkcsevaluate_add, false),
        viewBtn: false,//this.vaildData(this.permission.jkcsevaluate_view, true),
        delBtn: true,//this.vaildData(this.permission.jkcsevaluate_delete, true),
        editBtn: false,//this.vaildData(this.permission.jkcsevaluate_edit, true)
      };
    },
    jsId() {
      return this.JSuserInfo.js_Id
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  methods: {
    goBack() {
      this.showMainView();
    },
    rowSave(row, done, loading) {
      console.log(row)
      row.id = '0'
      row.groupId = this.csId
      add(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowUpdate(row, index, done, loading) {
      if (!contrastTime(row.job_start, row.job_end)) {
        this.$message({
          type: "warning",
          message: "开始时间不可大于结束时间!"
        });
        loading();
        return 0
      }
      row.csId = this.csId;

      update(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove({ids: row.id});
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove({ids: this.ids});
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        // getDetail(this.form.id).then(res => {
        //   this.form = res.data.data;
        // });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    onLoad(page, params = {}) {
      this.loading = true;
      params.groupId = this.csId;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    getSchoolUserSelect() {
      if (this.form.userType == '' || this.form.userType == null || this.form.schoolId == '' || this.form.schoolId == null) {
        return 0
      }
      let params = {
        groupId:this.csId,
        schoolId: this.form.schoolId,
        type: this.form.userType
      }
      getSchoolUserSelect(params).then(res => {
        const user = this.findObject(this.option.column, "userId");
        user.dicData = res.data.data;
      });
    },
  }
};
</script>

<style>
</style>
